package lock.livelock;

import java.math.BigDecimal;


/**
 * 活锁锁定示例
 * 原因：两个线程都相互谦让对方获取锁，而造成的等待
 * 改善：线程以随机间隔重试获取锁。这将使线程有公平的机会获得所需的锁。
 *
 * @author 86155
 * @date 2025/08/17
 */
public class LiveLockExample {

    /**
     * 实验
     *
     * @param args args
     */
    public static void main(String[] args) {
        Account a = new Account("a", new BigDecimal(5000));
        Account b = new Account("b", new BigDecimal(5000));
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                try {
                    a.transfer(b,50);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }, "T1").start();

            new Thread(() -> {
                try {
                    b.transfer(a,50);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }, "T2").start();
        }


    }


}
